<template>
    <div>
        <x-form ref="xForm" v-model="formData" :config="formConfig">
            <template #executionListener>
                <!-- <el-badge :value="executionListenerLength">
          <el-button size="small" @click="nodePermissions">查看/编辑</el-button>
        </el-badge> -->
                <el-button size="small" @click="nodePermissions">查看/编辑</el-button>
            </template>
            <template #formId>
                <el-input placeholder="请选择表单" class="input-with-select" v-model="formTypeValues">
                    <template slot="append">
                        <!--指定用户-->
                        <el-button style="padding-left: 7px" icon="el-icon-user" @click="formTypeCheck" />
                        <el-divider direction="vertical"></el-divider>
                        <!--选择表达式-->
                        <el-button style="padding-right: 7px" icon="el-icon-postcard"
                            @click="singleExpCheck('assignee')" />
                    </template>
                </el-input>
            </template>
            <template #checkSingleUser>
                <el-input placeholder="请选择人员" class="input-with-select" v-model="checkValues">
                    <template slot="append">
                        <!--指定用户-->
                        <el-button style="padding-left: 7px" icon="el-icon-user" @click="singleUserCheck" />
                        <el-divider direction="vertical"></el-divider>
                        <!--选择表达式-->
                        <el-button style="padding-right: 7px" icon="el-icon-postcard"
                            @click="singleExpCheck('assignee')" />
                    </template>
                </el-input>
            </template>
            <template #taskListener>
                <el-badge :value="taskListenerLength">
                    <el-button size="small" disabled>自动赋值</el-button>
                </el-badge>
            </template>
            <template #multiInstance>
                <el-badge :is-dot="hasMultiInstance">
                    <el-button size="small" disabled>自动赋值</el-button>
                </el-badge>
            </template>

            <template #checkMultipleUser>
                <el-input placeholder="请选择候选用户" class="input-with-select" v-model="checkValues">
                    <template slot="append">
                        <!--候选用户-->
                        <el-button style="padding-left: 7px" icon="el-icon-user" @click="multipleUserCheck" />
                        <el-divider direction="vertical"></el-divider>
                        <!--选择表达式-->
                        <el-button style="padding-right: 7px" icon="el-icon-postcard"
                            @click="singleExpCheck('candidateUsers')" />
                    </template>
                </el-input>
            </template>
            <template #checkRole>
                <el-input placeholder="请选择候选角色" class="input-with-select" v-model="checkValues">
                    <template slot="append">
                        <!--候选角色-->
                        <el-button style="padding-left: 7px" icon="el-icon-user" @click="multipleRoleCheck" />
                        <el-divider direction="vertical"></el-divider>
                        <!--选择表达式-->
                        <el-button style="padding-right: 7px" icon="el-icon-postcard"
                            @click="singleExpCheck('candidateGroups')" />
                    </template>
                </el-input>
            </template>
        </x-form>
        <executionListenerDialog v-if="dialogName === 'executionListenerDialog'" :element="element" :modeler="modeler"
            @close="finishExecutionListener" />
        <taskListenerDialog v-if="dialogName === 'taskListenerDialog'" :element="element" :modeler="modeler"
            @close="finishTaskListener" />
        <multiInstanceDialog v-if="dialogName === 'multiInstanceDialog'" :element="element" :modeler="modeler"
            @close="finishMultiInstance" />
        <!--选择人员-->
        <el-dialog title="选择人员" :visible.sync="userVisible" width="60%" :close-on-press-escape="false">
            <!-- :show-close="false" -->
            <flow-user :checkType="checkType" :selectValues="selectValues"
                @handleUserSelect="handleUserSelect"></flow-user>
            <span slot="footer" class="dialog-footer">
                <el-button @click="userVisible = false">取 消</el-button>
                <el-button type="primary" @click="checkUserComplete">确 定</el-button>
            </span>
        </el-dialog>
        <!--选择表达式-->
        <el-dialog title="选择表达式" :visible.sync="expVisible" width="60%" :close-on-press-escape="false">
            <!-- :show-close="false" -->
            <flow-exp :selectValues="selectValues" @handleSingleExpSelect="handleSingleExpSelect"></flow-exp>
            <span slot="footer" class="dialog-footer">
                <el-button @click="expVisible = false">取 消</el-button>
                <el-button type="primary" @click="checkExpComplete">确 定</el-button>
            </span>
        </el-dialog>
        <!--选择角色-->
        <el-dialog title="提报节点" :visible.sync="roleVisible" width="60%" :close-on-press-escape="false">
            <!-- :show-close="false" -->
            <div v-for="(item, index) in permissionList" :key="index">
                <div>
                    <p>
                        <span style="margin-right: 10px;">{{ item.pageName }}</span>
                        <el-radio-group v-model="item.formStatus" @input="(e) => permissionChange(e, item)"
                            :disabled="state == 'readonly'">
                            <el-radio :label="0">可编辑</el-radio>
                            <el-radio :label="1">只读</el-radio>
                            <el-radio :label="2">隐藏</el-radio>
                        </el-radio-group>
                    </p>
                    <div v-if="item.formStatus !== 2" style="margin-left: 25px;">
                        <li v-for='info in item.flowBusPageList' :key="info.name">
                            <span style="margin-right: 10px;">{{ info.name }}</span>
                            <el-radio-group v-model="info.formStatus" @input="(e) => permissionChange(e, item)"
                                :disabled="item.formStatus == 1">
                                <el-radio :label="0">可编辑</el-radio>
                                <el-radio :label="1">只读</el-radio>
                                <el-radio :label="2">隐藏</el-radio>
                            </el-radio-group>
                        </li>
                    </div>
                </div>

            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="roleVisible = false">取 消</el-button>
                <el-button type="primary" @click="checkRoleComplete">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import mixinPanel from "../../common/mixinPanel";
import executionListenerDialog from "./property/executionListener";
import taskListenerDialog from "./property/taskListener";
import multiInstanceDialog from "./property/multiInstance";
import { commonParse, userTaskParse } from "../../common/parseElement";
import { StrUtil } from "@/utils/StrUtil";
import FlowUser from "@/components/flow/User";
import FlowRole from "@/components/flow/Role";
import FlowExp from "@/components/flow/Expression";
import { listAllForm } from "@/api/flowable/form";
import {
    getFormDate,
    getCCUser,
    getPostRole,
    getApprovalRole,
    getApprovalUser,
} from "@/api/flowable/model";
import { Base64 } from "js-base64";

export default {
    components: {
        executionListenerDialog,
        taskListenerDialog,
        multiInstanceDialog,
        FlowUser,
        FlowRole,
        FlowExp,
    },
    mixins: [mixinPanel],
    props: {
        users: {
            type: Array,
            required: true,
        },
        groups: {
            type: Array,
            required: true,
        },
        exps: {
            type: Array,
            required: true,
        },
        config: {
            type: Array,
            required: true,
        },
        state: {
            required: false,
        },
    },
    data() {
        return {
            nodeIdList: [],
            sort: "",
            // 驳回节点
            rejectNode: [],
            // 抄送用户
            CCUserList: [],
            approvalList: [],
            allUserList: [],
            approvalList1: [],
            // 审批设置
            approvalSettings: [],
            // 选择表单
            formTypeValues: null,
            formTypeVisible: false,
            userTypeOption: [],
            dialogName: "",
            executionListenerLength: 0,
            taskListenerLength: 0,
            hasMultiInstance: false,
            userVisible: false,
            roleVisible: false,
            expVisible: false,
            formData: {
                copyUserIds: [],
            },
            assignee: null,
            candidateUsers: null,
            candidateGroups: null,
            // 选类型
            checkType: "single",
            // 选中的值
            checkValues: null,
            // 数据回显
            selectValues: null,
            // 用户列表
            userList: this.users,
            // 角色列表
            groupList: this.groups,
            // 表达式列表
            expList: this.exps,
            // 表达式类型
            expType: null,
            // 表单列表
            formList: [],
            permissionList: [], // 权限列表
            permissionRadio: 0, // 节点权限默认可编辑
            dicts: {
                flowTypeList: [
                    {
                        label: "提交人公司",
                        value: "1",
                    },
                    {
                        label: "业务公司",
                        value: "2",
                    },
                    {
                        label: "总部",
                        value: "3",
                    },
                ],
            },
            nodeName: '',// 点击当前节点表单的名称
            reject: false, // 是否显示驳回节点
        };
    },
    computed: {
        formConfig() {
            const _this = this;
            return {
                inline: false,
                item: [
                    {
                        xType: "input",
                        name: "id",
                        label: "节点 id",
                        rules: [{ required: true, message: "Id 不能为空" }],
                        // disabled: _this.state == "readonly",
                        disabled: true,
                    },
                    {
                        xType: "input",
                        name: "name",
                        label: "节点名称",
                        rules: [
                            { required: true, message: "节点名称不能为空" },
                        ],
                        disabled: _this.state == "readonly",
                    },
                    {
                        xType: "select",
                        name: "formId",
                        label: "选择表单",
                        clearable: true,
                        filter: true,
                        dic: _this.userTypeOption,
                        rules: [{ required: true, message: "表单不能为空" }],
                        disabled: _this.state == "readonly",
                    },
                    // {
                    //   xType: 'input',
                    //   name: 'banben',
                    //   label: '节点版本',
                    //   rules: [{ required: true, message: '节点版本不能为空' }]
                    // },

                    {
                        xType: "slot",
                        name: "executionListener",
                        label: "节点权限",
                        disabled: _this.state == "readonly",
                        rules: [
                            { required: true, message: "节点权限不能为空" },
                        ],
                    },
                    {
                        xType: "checkbox",
                        name: "auditConfig",
                        label: "审批设置",
                        dic: _this.approvalSettings,
                        show: _this.approvalSettings?.length > 0,
                        disabled: _this.state == "readonly",
                        rules: [
                            { required: true, message: "审批设置不能为空" },
                        ],
                    },
                    {
                        xType: "slot",
                        name: "taskListener",
                        label: "任务监听器",
                        disabled: _this.state == "readonly",
                    },
                    {
                        xType: "select",
                        name: "rejectActivity",
                        label: "驳回节点",
                        filterable: true,
                        multiple: true,
                        clearable: true,
                        collapseTags: true,
                        dic: _this.rejectNode,
                        disabled: _this.state == "readonly",
                        // show: _this.reject,
                        rules: [
                            { required: true, message: "驳回节点不能为空" },
                        ],
                    },
                    {
                        xType: "switch",
                        name: "isCopy",
                        label: "是否抄送",
                        activeText: "是",
                        inactiveText: "否",
                        disabled: _this.state == "readonly",
                        rules: [
                            { required: true, message: "是否抄送不能为空" },
                        ],
                    },
                    {
                        xType: "radio",
                        name: "isAvgUser",
                        label: "任务分配",
                        // clearable: true,
                        dic: [
                            {
                                label: "正常",
                                value: "0",
                            },
                            {
                                label: "平均",
                                value: "1",
                            },
                        ],
                        rules: [
                            { required: true, message: "任务分配不能为空" },
                        ],
                        disabled: _this.state == "readonly",
                    },
                    {
                        xType: "select",
                        name: "copyUserIds",
                        label: "抄送用户",
                        multiple: true,
                        filterable: true,
                        clearable: true,
                        collapseTags: true,
                        dic: _this.CCUserList,
                        disabled: _this.state == "readonly",
                        rules: [
                            { required: true, message: "抄送用户不能为空" },
                        ],
                        show: _this.formData.isCopy,
                    },
                    {
                        xType: "select",
                        name: "adjuctIds",
                        label: "调单用户",
                        multiple: true,
                        filterable: true,
                        clearable: true,
                        collapseTags: true,
                        dic: _this.CCUserList,
                        disabled: _this.state == "readonly",
                    },
                    {
                        xType: "switch",
                        name: "isPortUser",
                        label: "指定审批人员",
                        activeText: "是",
                        collapseTags: true,
                        inactiveText: "否",
                        disabled: _this.state == "readonly",
                        rules: [
                            { required: true, message: "指定审批人员不能为空" },
                        ],
                    },
                    {
                        xType: "select",
                        name: "candidateGroups",
                        label: "审批岗位",
                        filterable: true,
                        multiple: true,
                        collapseTags: true,
                        clearable: true,
                        dic: _this.approvalList,
                        show: !_this.formData?.isPortUser,
                        disabled: _this.state == "readonly",
                        rules: [
                            { required: true, message: "审批角色不能为空" },
                        ],
                    },

                    {
                        xType: "select",
                        name: "candidateUsers",
                        label: "审批用户",
                        filterable: true,
                        multiple: true,
                        collapseTags: true,
                        // clearable: true,
                        dic: _this.allUserList,
                        show: _this.formData?.isPortUser,
                        disabled: _this.state == "readonly",
                        rules: [
                            { required: true, message: "审批用户不能为空" },
                        ],
                    },
                    {
                        xType: "radio",
                        name: "flowType",
                        label: "节点审核",
                        clearable: true,
                        dic: _this.dicts.flowTypeList,
                        rules: [{ required: true, message: "表单不能为空" }],
                        show: !_this.formData.isPortUser,
                        rules: [
                            { required: true, message: "节点审核不能为空" },
                        ],
                    },
                    {
                        xType: "select",
                        name: "refuseUserIds",
                        label: "可拒绝用户",
                        multiple: true,
                        filterable: true,
                        collapseTags: true,
                        // clearable: true,
                        dic: _this.allUserList,
                        disabled: _this.state == "readonly",
                        rules: [
                            { required: true, message: "可拒绝用户不能为空" },
                        ],
                        // rules: [{ required: true, message: '表单不能为空' }],
                    },
                    // {
                    //   xType: 'input',
                    //   name: 'documentation',
                    //   label: '节点描述'
                    // },

                    // {
                    //     xType: "select",
                    //     name: "userType",
                    //     label: "用户类型",
                    //     // clearable: true,
                    //     dic: _this.userTypeOption,
                    //     // rules: [{ required: true, message: '用户类型不能为空' }],
                    //     show: !!_this.showConfig.userType,
                    // },
                    {
                        xType: "slot",
                        name: "checkSingleUser",
                        label: "指定人员",
                        // rules: [{ required: true, message: '指定人员不能为空' }],
                        show:
                            !!_this.showConfig.assignee &&
                            _this.formData.userType === "assignee",
                        disabled: _this.state == "readonly",
                        rules: [
                            { required: true, message: "指定人员不能为空" },
                        ],
                    },
                    {
                        xType: "slot",
                        name: "checkMultipleUser",
                        label: "候选人员",
                        // rules: [{ required: true, message: '候选人员不能为空' }],
                        show:
                            !!_this.showConfig.candidateUsers &&
                            _this.formData.userType === "candidateUsers",
                        disabled: _this.state == "readonly",
                        rules: [
                            { required: true, message: "候选人员不能为空" },
                        ],
                    },
                    {
                        xType: "slot",
                        name: "checkRole",
                        label: "候选角色",
                        // rules: [{ required: true, message: '候选角色不能为空' }],
                        show:
                            !!_this.showConfig.candidateGroups &&
                            _this.formData.userType === "candidateGroups",
                        disabled: _this.state == "readonly",
                        rules: [
                            { required: true, message: "候选角色不能为空" },
                        ],
                    },
                    // {
                    //   xType: 'slot',
                    //   name: 'multiInstance',
                    //   label: '多实例'
                    // },
                    // {
                    //     xType: "switch",
                    //     name: "async",
                    //     label: "异步",
                    //     activeText: "是",
                    //     inactiveText: "否",
                    //     show: !!_this.showConfig.async,
                    // },
                    // {
                    //     xType: "input",
                    //     name: "priority",
                    //     label: "优先级",
                    //     show: !!_this.showConfig.priority,
                    // },
                    // {
                    //   xType: 'input',
                    //   name: 'formId',
                    //   label: '表单标识key',
                    //   show: !!_this.showConfig.formId
                    // },
                    // {
                    //     xType: "select",
                    //     name: "formId",
                    //     label: "表单标识key",
                    //     clearable: true,
                    //     dic: {
                    //         data: _this.formList,
                    //         label: "formName",
                    //         value: "formId",
                    //     },
                    //     show: !!_this.showConfig.formId,
                    // },
                    // {
                    //     xType: "input",
                    //     name: "skipExpression",
                    //     label: "跳过表达式",
                    //     show: !!_this.showConfig.skipExpression,
                    // },
                    {
                        xType: "switch",
                        name: "isForCompensation",
                        label: "是否为补偿",
                        activeText: "是",
                        inactiveText: "否",
                        show: !!_this.showConfig.isForCompensation,
                        disabled: _this.state == "readonly",
                    },
                    {
                        xType: "switch",
                        name: "triggerable",
                        label: "服务任务可触发",
                        activeText: "是",
                        inactiveText: "否",
                        show: !!_this.showConfig.triggerable,
                        disabled: _this.state == "readonly",
                    },
                    {
                        xType: "switch",
                        name: "autoStoreVariables",
                        label: "自动存储变量",
                        activeText: "是",
                        inactiveText: "否",
                        show: !!_this.showConfig.autoStoreVariables,
                        disabled: _this.state == "readonly",
                    },
                    {
                        xType: "input",
                        name: "ruleVariablesInput",
                        label: "输入变量",
                        show: !!_this.showConfig.ruleVariablesInput,
                        disabled: _this.state == "readonly",
                    },
                    {
                        xType: "input",
                        name: "rules",
                        label: "规则",
                        show: !!_this.showConfig.rules,
                        disabled: _this.state == "readonly",
                    },
                    {
                        xType: "input",
                        name: "resultVariable",
                        label: "结果变量",
                        show: !!_this.showConfig.resultVariable,
                        disabled: _this.state == "readonly",
                    },
                    {
                        xType: "switch",
                        name: "exclude",
                        label: "排除",
                        activeText: "是",
                        inactiveText: "否",
                        show: !!_this.showConfig.exclude,
                        disabled: _this.state == "readonly",
                    },
                    {
                        xType: "input",
                        name: "class",
                        label: "类",
                        show: !!_this.showConfig.class,
                        disabled: _this.state == "readonly",
                    },
                    // {
                    //     xType: "datePicker",
                    //     type: "datetime",
                    //     valueFormat: "yyyy-MM-ddTHH:mm:ss",
                    //     name: "dueDate",
                    //     label: "到期时间",
                    //     show: !!_this.showConfig.dueDate,
                    // },
                ],
            };
        },
    },
    watch: {

        "formData.id": function (val) {
            // console.log(val, 'valval')
            // if (val) {
            //     const id = val.split('_')[1]
            //     if (id == '1') {
            //         this.reject = false
            //     } else {
            //         this.reject = true
            //     }
            // }
            if (StrUtil.isNotBlank(val)) {
                this.updateProperties({ "flowable:id": val });
            } else {
                // 删除xml中已选择表单信息
                delete this.element.businessObject[`id`];
            }
        }, // id
        "formData.name": function (val) {
            if (StrUtil.isNotBlank(val)) {
                this.updateProperties({ "flowable:name": val });
            } else {
                // 删除xml中已选择表单信息
                delete this.element.businessObject[`name`];
            }
        }, // 名称
        "formData.formId": function (val, oldVal) {
            this.userTypeOption.map((res, index) => {
                if (res.id == val) {
                    // 设置监听器
                    let list = [];
                    let obj = {
                        event: "create",
                        callingMethod: res.beforeCallingMethod
                            ? res.beforeCallingMethod
                            : "",
                    };
                    let obj1 = {
                        event: "complete",
                        callingMethod: res.afterCallingMethod
                            ? res.afterCallingMethod
                            : "",
                    };
                    list.push(obj);
                    list.push(obj1);
                    this.updateElement(list);
                    this.getFormList(this.$route.query.category, res.sort, val);
                }
                return res;
            });
            if (StrUtil.isNotBlank(oldVal)) {
                delete this.element.businessObject.$attrs[`flowable:${oldVal}`];
                delete this.formData[oldVal];
                // 清除已选人员数据
                this.checkValues = "";
                this.selectValues = null;
                // 删除xml中已选择数据类型节点
                delete this.element.businessObject.$attrs[`flowable:formId`];
            }
            if (!val) {
                this.permissionList = [];
                delete this.element.businessObject.$attrs[
                    `flowable:pageAddress`
                ];
                delete this.element.businessObject.$attrs[
                    `flowable:customForm`
                ];
            }
            // 写入userType节点信息到xml
            this.updateProperties({ "flowable:formId": val });
        }, // 选择表单
        "formData.banben": function (val) {
            if (StrUtil.isNotBlank(val)) {
                this.updateProperties({ "flowable:banben": val });
            } else {
                // 删除xml中已选择表单信息
                delete this.element.businessObject[`banben`];
            }
        }, // 节点版本
        "formData.auditConfig": function (val, oldVal) {
            if (StrUtil.isNotBlank(oldVal)) {
                delete this.element.businessObject.$attrs[`flowable:${oldVal}`];
                delete this.formData[oldVal];
                // 清除已选人员数据
                this.checkValues = "";
                this.selectValues = null;
                // 删除xml中已选择数据类型节点
                delete this.element.businessObject.$attrs[
                    `flowable:auditConfig`
                ];
            }
            // 写入userType节点信息到xml
            this.updateProperties({ "flowable:auditConfig": val });
        }, //审批设置
        "formData.rejectActivity": function (val, oldVal) {
            if (StrUtil.isNotBlank(oldVal)) {
                delete this.element.businessObject.$attrs[`flowable:${oldVal}`];
                delete this.formData[oldVal];
                // 清除已选人员数据
                this.checkValues = "";
                this.selectValues = null;
                // 删除xml中已选择数据类型节点
                delete this.element.businessObject.$attrs[
                    `flowable:rejectActivity`
                ];
            }
            // 写入userType节点信息到xml
            this.updateProperties({ "flowable:rejectActivity": val });
        },
        // 驳回节点
        "formData.isCopy": function (val) {
            if (val === false) {
                this.formData.copyUserIds = [];
            }
            if (StrUtil.isNotBlank(val)) {
                this.updateProperties({ "flowable:isCopy": val });
            }
        }, // 是否抄送
        "formData.copyUserIds": function (val, oldVal) {
            if (StrUtil.isNotBlank(oldVal)) {
                delete this.element.businessObject.$attrs[`flowable:${oldVal}`];
                delete this.formData[oldVal];
                // 清除已选人员数据
                this.checkValues = "";
                this.selectValues = null;
                // 删除xml中已选择数据类型节点
                delete this.element.businessObject.$attrs[
                    `flowable:copyUserIds`
                ];
            }
            // 写入userType节点信息到xml
            this.updateProperties({ "flowable:copyUserIds": val });
        },
        //抄送用户
        "formData.candidateGroups": function (val, oldVal) {
            // let model = this.modeler.get("elementRegistry")._elements;
            // let list = [];
            // let info = [];
            // for (let key in model) {
            //     list.push(model[key]);
            // }
            // list.map((res) => {
            //     if (
            //         res.element.type == "bpmn:Task" ||
            //         res.element.type == "bpmn:UserTask"
            //     ) {
            //         let obj = {
            //             label: "",
            //             value: "",
            //         };
            //         obj.label = res.element.businessObject.name;
            //         obj.value = res.element.businessObject.id;
            //         if (obj.label !== undefined) {
            //             info.push(obj);
            //         }
            //     }
            // });
            // this.rejectNode = Array.from(
            //     new Set(info.map((item) => JSON.stringify(item)))
            // ).map((item) => JSON.parse(item));
            // if (val.length > 0) {
            //     this.getAllUser(val.toString());
            // }

            if (StrUtil.isNotBlank(oldVal)) {
                delete this.element.businessObject.$attrs[`flowable:${oldVal}`];
                delete this.formData[oldVal];
                // 清除已选人员数据
                this.checkValues = "";
                this.selectValues = null;
                // 删除xml中已选择数据类型节点
                delete this.element.businessObject.$attrs[
                    `flowable:candidateGroups`
                ];
            }
            // 写入userType节点信息到xml
            this.updateProperties({ "flowable:candidateGroups": val });
        },
        //调单用户
        "formData.adjuctIds": function (val, oldVal) {
            if (StrUtil.isNotBlank(oldVal)) {
                delete this.element.businessObject.$attrs[`flowable:${oldVal}`];
                delete this.formData[oldVal];
                // 清除已选人员数据
                this.checkValues = "";
                this.selectValues = null;
                // 删除xml中已选择数据类型节点
                delete this.element.businessObject.$attrs[
                    `flowable:adjuctIds`
                ];
            }
            // 写入userType节点信息到xml
            this.updateProperties({ "flowable:adjuctIds": val });
        },
        "formData.isAvgUser": function (val) {
            if (val == "") {
                this.formData.isAvgUser = "0";
            }
            if (StrUtil.isNotBlank(val)) {
                this.updateProperties({ "flowable:isAvgUser": val });
            }
        },
        "formData.flowType": function (val) {
            if (StrUtil.isNotBlank(val)) {
                this.updateProperties({ "flowable:flowType": val });
            }
        },
        //审批角色
        "formData.isPortUser": function (val) {
            if (val == "") {
                this.formData.isPortUser = false;
            }

            if (StrUtil.isNotBlank(val)) {
                // this.formData.candidateUsers
                // let ids = this.allUserList;
                this.updateProperties({ "flowable:isPortUser": val });
                if (val) {
                    this.formData.flowType = "";
                    this.formData.candidateGroups = "";
                    delete this.element.businessObject.$attrs[
                        `flowable:flowType`
                    ];
                    delete this.element.businessObject.$attrs[
                        `flowable:candidateGroups`
                    ];
                    // this.updateProperties({ "flowable:candidateGroups": "" });
                } else {
                    this.formData.candidateUsers = "";
                    delete this.element.businessObject.$attrs[
                        `flowable:candidateUsers`
                    ];
                    // this.updateProperties({ "flowable:candidateUsers": "" });
                }
            }
        }, // 是否指定审批人员
        "formData.candidateUsers": function (val, oldVal) {
            if (StrUtil.isNotBlank(oldVal)) {
                delete this.element.businessObject.$attrs[`flowable:${oldVal}`];
                delete this.formData[oldVal];
                // 清除已选人员数据
                this.checkValues = "";
                this.selectValues = null;
                // 删除xml中已选择数据类型节点
                delete this.element.businessObject.$attrs[
                    `flowable:candidateUsers`
                ];
            }
            // 写入userType节点信息到xml
            this.updateProperties({ "flowable:candidateUsers": val });
        }, //审批用户
        "formData.refuseUserIds": function (val, oldVal) {
            if (StrUtil.isNotBlank(oldVal)) {
                delete this.element.businessObject.$attrs[`flowable:${oldVal}`];
                delete this.formData[oldVal];
                // 清除已选人员数据
                this.checkValues = "";
                this.selectValues = null;
                // 删除xml中已选择数据类型节点
                delete this.element.businessObject.$attrs[
                    `flowable:refuseUserIds`
                ];
            }
            // 写入userType节点信息到xml
            this.updateProperties({ "flowable:refuseUserIds": val });
        }, //可拒绝用户
        "formData.dueDate": function (val) {
            if (StrUtil.isNotBlank(val)) {
                this.updateProperties({ "flowable:dueDate": val });
            }
        },
        "formData.priority": function (val) {
            if (StrUtil.isNotBlank(val)) {
                this.updateProperties({ "flowable:priority": val });
            }
        },
        "formData.skipExpression": function (val) {
            if (StrUtil.isNotBlank(val)) {
                this.updateProperties({ "flowable:skipExpression": val });
            } else {
                delete this.element.businessObject.$attrs[
                    `flowable:skipExpression`
                ];
            }
        },
        "formData.isForCompensation": function (val) {
            if (StrUtil.isNotBlank(val)) {
                this.updateProperties({ isForCompensation: val });
            }
        },
        "formData.triggerable": function (val) {
            if (StrUtil.isNotBlank(val)) {
                this.updateProperties({ "flowable:triggerable": val });
            }
        },
        "formData.class": function (val) {
            if (StrUtil.isNotBlank(val)) {
                this.updateProperties({ "flowable:class": val });
            }
        },
        "formData.autoStoreVariables": function (val) {
            if (StrUtil.isNotBlank(val)) {
                this.updateProperties({ "flowable:autoStoreVariables": val });
            }
        },
        "formData.exclude": function (val) {
            if (StrUtil.isNotBlank(val)) {
                this.updateProperties({ "flowable:exclude": val });
            }
        },
        "formData.ruleVariablesInput": function (val) {
            if (StrUtil.isNotBlank(val)) {
                this.updateProperties({ "flowable:ruleVariablesInput": val });
            }
        },
        "formData.rules": function (val) {
            if (StrUtil.isNotBlank(val)) {
                this.updateProperties({ "flowable:rules": val });
            }
        },
        "formData.resultVariable": function (val) {
            if (StrUtil.isNotBlank(val)) {
                this.updateProperties({ "flowable:resultVariable": val });
            }
        },
    },
    async created() {
        this.getApplySett();
        this.getAllUser();
        // 获取表单列表
        this.getFormList(this.$route.query.category, "");
        // 获取审批设置
        this.getCcUser();
        this.getAllRole();
        let cache = commonParse(this.element);
        cache.auditConfig = cache.auditConfig
            ? this.toNumber(cache.auditConfig)
            : null;
        cache.candidateGroups = cache.candidateGroups
            ? this.toNumber(cache.candidateGroups)
            : null;

        cache.candidateUsers = cache.candidateUsers
            ? this.toNumber(cache.candidateUsers)
            : null;
        cache.copyUserIds = cache.copyUserIds
            ? this.toNumber(cache.copyUserIds)
            : null;
        cache.adjuctIds = cache.adjuctIds
            ? this.toNumber(cache.adjuctIds)
            : null;
        cache.refuseUserIds = cache.refuseUserIds
            ? this.toNumber(cache.refuseUserIds)
            : null;
        this.permissionList = cache.executionListener
            ? JSON.parse(Base64.decode(cache.executionListener))
            : null;
        cache.rejectActivity = cache.rejectActivity
            ? this.toNumber(cache.rejectActivity)
            : null;

        cache.isCopy === "true" || cache.isCopy === true
            ? (cache.isCopy = true)
            : (cache.isCopy = false);
        this.formData = cache;
        this.computedExecutionListenerLength();
        this.computedTaskListenerLength();
        this.computedHasMultiInstance();
        if (typeof this.formData.isPortUser == "string") {
            this.formData.isPortUser == "true"
                ? (this.formData.isPortUser = true)
                : (this.formData.isPortUser = false);
        }
        if (typeof this.formData.auditConfig == "string") {
            this.formData.auditConfig = this.formData.auditConfig?.split(",");
        }
        // this.formData.auditConfig.map((item) => {
        //     let n = item * 1;
        //     return n;
        // });
    },
    mounted() {
        this.formData.taskListener = this.element.businessObject;
        let list = []
        // let nodeID = JSON.parse(JSON.stringify(this.element.id))
        // this.element.incoming.map((res) => {
        //     res?.parent?.children?.map((item) => {
        //         if (item.type == 'bpmn:SequenceFlow') {
        //             let obj = {
        //                 start: item.source.id,
        //                 end: item.target.id,
        //             }
        //             list.push(obj)
        //         }
        //     })
        // })
        // this.getNodeId(list, nodeID)
    },
    methods: {
        getNodeId(data, nodeID) {
            data.map((info) => {
                if (info.end == nodeID) {
                    this.nodeIdList.push(info)
                    this.getNodeId(data, info.start)
                }
            })
        },
        getApplySett() {
            return new Promise((resolve) => {
                this.getDicts("apply_sett")
                    .then((res) => {
                        this.approvalSettings = [];
                        res.data.map((item) => {
                            item.label = item.dictLabel;
                            item.value = item.dictValue?.toString();
                            this.approvalSettings.push(item);
                        });
                    })
                    .finally(() => {
                        resolve();
                    });
            });
        },
        updateElement(info) {
            this.formData.taskListener = info;
            if (this.formData.taskListener?.length) {
                let extensionElements =
                    this.element.businessObject.get("extensionElements");
                if (!extensionElements) {
                    extensionElements = this.modeler
                        .get("moddle")
                        .create("bpmn:ExtensionElements");
                }
                // 清除旧值

                extensionElements.values =
                    extensionElements.values?.filter(
                        (item) => item.$type !== "flowable:TaskListener"
                    ) ?? [];
                this.formData.taskListener.forEach((item) => {
                    if (item.callingMethod && item.event) {
                        const taskListener = this.modeler
                            .get("moddle")
                            .create("flowable:TaskListener");

                        taskListener["event"] = item.event;
                        // taskListener["class"] = item.callingMethod;
                        taskListener[
                            "delegateExpression"
                        ] = `\$\{${item.callingMethod}\}`;
                        extensionElements.get("values").push(taskListener);
                    }
                });
                this.updateProperties({ extensionElements: extensionElements });
            } else {
                const extensionElements =
                    this.element.businessObject[`extensionElements`];

                if (extensionElements) {
                    extensionElements.values =
                        extensionElements.values?.filter(
                            (item) => item.$type !== "flowable:TaskListener"
                        ) ?? [];
                }
            }
        },
        // 审批权限改变
        permissionChange(e, info) {

        },
        // 字符串转数字
        toNumber(info) {
            let list = [];
            if (typeof info === "string") {
                let list1 = info.split(",");
                if (list1.length > 0) {
                    list1.map((res) => {
                        list.push(res?.toString());
                    });
                }
            } else if (typeof info === "object") {
                if (info.length > 0) {
                    info.map((res) => {
                        list.push(res?.toString());
                    });
                }
            }

            return list;
        },
        // 获取所有人员
        getAllUser(id) {
            // getApprovalUser({ roleIds: id }).then((res) => {
            //     res.data.map((item) => {
            //         item.label = item.userName;
            //         item.value = Number(item.userId);
            //         this.allUserList.push(item);
            //     });
            // });
            // getCCUser().then((res) => {
            //     this.allUserList = [];
            //     // res.data.map((item) => {
            //     //     item.label = item.nickName;
            //     //     item.value = Number(item.userId);
            //     //     this.CCUserList.push(item);
            //     // });
            //     res.data.map((item) => {
            //         item.label = item.userInfo;
            //         item.value = Number(item.userId);
            //         this.allUserList.push(item);
            //     });
            // });
        },
        // 获取抄送人员
        getCcUser() {
            getCCUser().then((res) => {
                this.CCUserList = [];
                res.data.map((item) => {
                    let obj = {
                        label: item.userName,
                        value: item.userId?.toString(),
                    };

                    this.CCUserList.push(obj);
                    let pbjU = {
                        label: item.userName,
                        value: item.userId?.toString(),
                    };
                    //  item.label = item.userInfo;
                    // item.value = Number(item.userId);
                    this.allUserList.push(pbjU);
                });
            });
        },
        // 获取所有岗位信息
        getAllRole() {
            let that = this;
            getPostRole().then((res) => {
                this.approvalList = [];
                res.data.map((item) => {
                    let obj = {
                        label: item.postName,
                        value: item.postId?.toString(),
                    };
                    // item.label = item.roleName;
                    // item.value = Number(item.roleId);
                    that.approvalList.push(obj);
                });
            });
        },
        // 点击节点权限
        nodePermissions() {
            this.roleVisible = true;
        },
        // 获取表单列表
        getFormList(type, num, currentVal) {
            if (this.userTypeOption?.length == 0) {
                let parentNodes = this.getAllParentNodes(this.element);
                let oldFormIds = [];
                parentNodes?.map((item) => {
                    oldFormIds.push(
                        item?.businessObject?.$attrs?.["flowable:formId"]
                    );
                    this.rejectNode.push({
                        label: item?.businessObject?.$attrs?.["flowable:name"],
                        value: item?.businessObject?.$attrs?.["flowable:id"],
                    });
                    // 第一个节点没有驳回节点
                    if (this.rejectNode.length > 0) {
                        this.reject = true
                    } else {
                        this.reject = false
                    }
                });
                getFormDate({ bizType: type }).then((res) => {
                    if (res.data.length > 0) {
                        res.data.map((item) => {
                            // if (!oldFormIds?.includes(item.id)) {
                            if (true) {
                                this.userTypeOption.push({
                                    ...item,
                                    label: item.formName,
                                    value: item.id?.toString(),
                                });
                            }
                        });
                    }
                });
            } else {
                if (
                    currentVal !== null &&
                    currentVal !== undefined &&
                    currentVal !== ""
                ) {
                    let formIndex = this.userTypeOption.findIndex((e) => {
                        return e.id == currentVal;
                    });
                    if (formIndex !== -1) {
                        // 设置节点权限
                        // this.initPermissionList(formIndex);
                        // 设置节点页面
                        this.setPageAddress(formIndex);
                    }
                }
            }

            // if (num !== null && num !== "") {
            //     getFormDate({ bizType: type, sort: num }).then((res) => {
            //         if (res.data.length > 0) {
            //             res.data.map((item) => {
            //                 let obj = {
            //                     formName: item.formName,
            //                     formStatus: 0,
            //                 };
            //                 this.permissionList.push(obj);
            //                 // this.updateProperties({
            //                 //     "flowable:pageAddress": item.pageAddress,
            //                 // });
            //             });
            //         }
            //     });
            //     if (currentVal !== undefined && currentVal !== null) {
            //     }
            // } else {
            //     getFormDate({ bizType: type }).then((res) => {
            //         if (res.data.length > 0) {
            //             res.data.map((item) => {
            //                 item.label = item.formName;
            //                 item.value = item.id;
            //                 this.userTypeOption.push(item);
            //             });
            //         }
            //     });
            // }
        },
        setPageAddress(formIndex) {
            let pageArr = [];
            this.permissionList = [];
            let same = false;
            this.userTypeOption?.reduce((prev, next) => {
                if (prev.pageAddress === next.pageAddress) {
                    same = true;
                } else {
                    same = false;
                }
                return prev;
            });
            this.userTypeOption?.map((item, index) => {
                if (index == formIndex) {
                    if (item.formType == 1) {
                        let obj = {
                            pageName: item.formName,
                            formType: item.formType,
                            pageAddress: item.pageAddress,
                            customForm: item.customForm,
                            formStatus: 0,
                            flowBusPageList: item.flowBusPageList
                        };
                        this.permissionList.push(obj);
                        pageArr.push(obj);
                    }
                }
            });
            this.checkRoleComplete();
            if (pageArr.length > 0) {
                this.updateProperties({
                    "flowable:pageAddress": JSON.stringify(pageArr),
                });
            }
        },
        initPermissionList(formIndex) {
            this.permissionList = [];
            let itemIndex = this.permissionList?.findIndex((e) => {
                return e.formName === item.formName;
            });

            this.userTypeOption?.map((item, index) => {
                if (index == formIndex) {
                    let pages = item?.pageAddress?.split(",") ?? [];
                    let formPages = pages.map((page, index) => {
                        return {
                            pageName: `页面${index + 1}`,
                            pageAddress: page,
                            formStatus: 0,
                        };
                    });
                    let obj = {
                        formName: item.formName,
                        formPages: formPages,
                    };

                    if (itemIndex == -1) {
                        this.permissionList.push(obj);
                    }
                }
            });
        },
        computedExecutionListenerLength() {
            this.executionListenerLength =
                this.element.businessObject.extensionElements?.values?.filter(
                    (item) => item.$type === "flowable:ExecutionListener"
                ).length ?? 0;
        },
        computedTaskListenerLength() {
            this.taskListenerLength =
                this.element.businessObject.extensionElements?.values?.filter(
                    (item) => item.$type === "flowable:TaskListener"
                ).length ?? 0;
        },
        computedHasMultiInstance() {
            if (this.element.businessObject.loopCharacteristics) {
                this.hasMultiInstance = true;
            } else {
                this.hasMultiInstance = false;
            }
        },
        // 选择表单
        /*单选人员*/
        formTypeCheck() {
            this.userVisible = true;
            this.checkType = "single";
        },
        // 获取表单信息
        getListForm() {
            listAllForm().then((res) => {
                res.data.forEach((item) => {
                    item.formId = item.formId.toString();
                });
                this.formList = res.data;
            });
        },
        // 设计器右侧表单数据回显
        checkValuesEcho() {
            const that = this;
            const attrs = that.element.businessObject.$attrs;
            const businessObject = that.element.businessObject;
            // 指定用户
            if (attrs.hasOwnProperty("flowable:assignee")) {
                const val = attrs["flowable:assignee"];
                // 查找是否动态指定人员(选中流程表达式)
                if (attrs["flowable:dataType"] === "dynamic") {
                    this.checkValues = that.expList.find(
                        (item) => item.expression == val
                    ).name;
                    this.selectValues = that.expList.find(
                        (item) => item.expression == val
                    ).id;
                } else {
                    this.checkValues = that.userList.find(
                        (item) => item.userId == val
                    ).nickName;
                    this.selectValues = that.userList.find(
                        (item) => item.userId == val
                    ).userId;
                }
                // 候选用户
            } else if (attrs.hasOwnProperty("flowable:candidateUsers")) {
                const val = attrs["flowable:candidateUsers"];
                if (attrs["flowable:dataType"] === "dynamic") {
                    this.checkValues = that.expList.find(
                        (item) => item.expression == val
                    ).name;
                    this.selectValues = that.expList.find(
                        (item) => item.expression == val
                    ).id;
                } else {
                    const newArr = that.userList.filter((i) =>
                        val.split(",").includes(i.userId)
                    );
                    this.checkValues = newArr
                        .map((item) => item.nickName)
                        .join(",");
                    this.selectValues = newArr
                        .map((item) => item.userId)
                        .join(",");
                }
            } else if (
                businessObject.hasOwnProperty("candidateGroups") ||
                attrs.hasOwnProperty("flowable:candidateGroups")
            ) {
                // 候选角色信息
                const val =
                    businessObject["candidateGroups"] ||
                    attrs["flowable:candidateGroups"];
                if (attrs["flowable:dataType"] === "dynamic") {
                    this.checkValues = that.expList.find(
                        (item) => item.expression == val
                    ).name;
                    this.selectValues = that.expList.find(
                        (item) => item.expression == val
                    ).id;
                } else {
                    const newArr = that.groupList.filter((i) =>
                        val.split(",").includes(i.roleId)
                    );
                    this.checkValues = newArr
                        .map((item) => item.roleName)
                        .join(",");
                    this.selectValues = newArr
                        .map((item) => item.roleId)
                        .join(",");
                }
            }
        },
        finishExecutionListener() {
            if (this.dialogName === "executionListenerDialog") {
                this.computedExecutionListenerLength();
            }
            this.dialogName = "";
        },
        finishTaskListener() {
            if (this.dialogName === "taskListenerDialog") {
                this.computedTaskListenerLength();
            }
            this.dialogName = "";
        },
        finishMultiInstance() {
            if (this.dialogName === "multiInstanceDialog") {
                this.computedHasMultiInstance();
            }
            this.dialogName = "";
        },
        /*单选人员*/
        singleUserCheck() {
            this.userVisible = true;
            this.checkType = "single";
        },
        /*多选人员*/
        multipleUserCheck() {
            this.userVisible = true;
            this.checkType = "multiple";
        },
        /*单选角色*/
        singleRoleCheck() {
            this.roleVisible = true;
            this.checkType = "single";
        },
        /*多选角色*/
        multipleRoleCheck() {
            this.roleVisible = true;
            this.checkType = "multiple";
        },
        /*单选表达式*/
        singleExpCheck(expType) {
            this.expVisible = true;
            this.expType = expType;
        },
        // 选中表达式
        handleSingleExpSelect(selection) {
            this.deleteFlowAttar();
            this.updateProperties({ "flowable:dataType": "dynamic" });
            if ("assignee" === this.expType) {
                this.updateProperties({
                    "flowable:assignee": selection.expression,
                });
            } else if ("candidateUsers" === this.expType) {
                this.updateProperties({
                    "flowable:candidateUsers": selection.expression,
                });
            } else if ("candidateGroups" === this.expType) {
                this.updateProperties({
                    "flowable:candidateGroups": selection.expression,
                });
            } else if ("adjuctIds" === this.expType) {
                this.updateProperties({
                    "flowable:adjuctIds": selection.expression,
                });
            }
            this.checkValues = selection.name;
            this.expType = null;
        },
        // 用户选中数据
        handleUserSelect(selection) {
            const that = this;
            if (selection) {
                that.deleteFlowAttar();
                that.updateProperties({ "flowable:dataType": "fixed" });
                if (selection instanceof Array) {
                    const userIds = selection.map((item) => item.userId);
                    const nickName = selection.map((item) => item.nickName);
                    that.updateProperties({
                        "flowable:candidateUsers": userIds.join(","),
                    });
                    that.checkValues = nickName.join(",");
                } else {
                    that.updateProperties({
                        "flowable:assignee": selection.userId,
                    });
                    that.checkValues = selection.nickName;
                }
            }
        },
        // 角色选中数据
        handleRoleSelect(selection, name) {
            const that = this;
            if (selection && name) {
                that.deleteFlowAttar();
                that.updateProperties({ "flowable:dataType": "fixed" });
                that.updateProperties({
                    "flowable:candidateGroups": selection,
                });
                that.checkValues = name;
            }
        },
        /*用户选中赋值*/
        checkUserComplete() {
            this.userVisible = false;
            this.checkType = "";
        },
        /*节点权限确定*/
        checkRoleComplete() {
            let a = Base64.encode(JSON.stringify(this.permissionList));
            delete this.element.businessObject[`executionListener`];
            this.updateProperties({ "flowable:executionListener": a });
            this.roleVisible = false;
        },
        /*表达式选中赋值*/
        checkExpComplete() {
            this.expVisible = false;
        },
        // 删除节点
        deleteFlowAttar() {
            delete this.element.businessObject.$attrs[`flowable:dataType`];
            delete this.element.businessObject.$attrs[`flowable:assignee`];
            delete this.element.businessObject.$attrs[
                `flowable:candidateUsers`
            ];
            delete this.element.businessObject.$attrs[
                `flowable:candidateGroups`
            ];
        },
        getFirstTasks() {
            let firstTasksList = [];
            //开始节点的出线
            const firstFlow = this.modeler
                .getModeler()
                .get("elementRegistry")
                .find(function (item) {
                    return item.type == "bpmn:StartEvent";
                })?.outgoing[0];
            if (
                firstFlow &&
                firstFlow.target &&
                firstFlow.target.type == "bpmn:UserTask"
            ) {
                firstTasksList.push(firstFlow.target);
            } else {
                //开始节点连接网关
                firstFlow.target?.outgoing.forEach((ele) => {
                    firstTasksList.push(ele.target);
                });
            }
            return firstTasksList;
        },
        getAllParentNodes(node) {
            const parentNodes = [];
            const incoming = node.incoming || [];

            for (const connection of incoming) {
                if (connection.source) {
                    if (connection.source?.type == "bpmn:UserTask") {
                        parentNodes.push(connection.source);
                    }
                    // 默认把开始节点添加到驳回下拉框里面
                    if (connection.source?.type == "bpmn:StartEvent") {
                        parentNodes.push(connection.source);
                    }
                    parentNodes.push(
                        ...this.getAllParentNodes(connection.source)
                    );
                }
            }
            let ids = [];
            let list = parentNodes.filter((item) => {
                if (!ids.includes(item.id)) {
                    ids.push(item.id);
                    return true;
                } else {
                    return false;
                }
            });
            return list;
        },
    },
};
</script>

<style lang="scss" scoped>
::v-deep .el-select {
    .el-select__tags {
        .el-tag {
            max-width: 100px !important;
        }
    }
}
</style>
